import { GZCA } from '@/utils/gzca.js';
import store from '@/store/index.js';

function getSignCert() {
  return initSocket();
}

function initSocket() {
  GZCA.init((res) => {
    if (res) {
      return getUkeyList();
    } else{
      store.dispatch('snackbar/openSnackbar',{
        msg: '连接失败',
        color: 'error'
      })
    }
  });
}

//获取UKEY列表
function getUkeyList() {
  const CertType = 1;
  GZCA.GZCA_GetCertList(true, CertType, function (res) {
    if (res.success) {
      return getCert(res.ContainerName, CertType)
    }else{
      store.dispatch('snackbar/openSnackbar',{
        msg: res.msg,
        color: 'error'
      })
    }
  });
}

//获取签名证书base64
function getCert(ContainerName, CertType) {
  GZCA.GZCA_ExportCert(ContainerName, CertType, function (res) {
    if (res.success) {
      return getSn(res.CertB64);
    }else{
      store.dispatch('snackbar/openSnackbar',{
        msg: res.msg,
        color: 'error'
      })
    }
  });
}

//获取签名证书序列号
function getSn(CertB64) {
  GZCA.GZCA_GetCertInfo(CertB64, function (res) {
    if (res.success) {
      return res.CertSerial;
    }else{
      store.dispatch('snackbar/openSnackbar',{
        msg: res.msg,
        color: 'error'
      })
    }
  });
}

export {getSignCert}